package org.androidpush.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.androidpush.R;
import org.androidpush.client.LogUtil;
import org.androidpush.greendao.SelectCouInfo;
import org.androidpush.greendao.SelectCouInfoDao;
import org.androidpush.utils.ConstantUtils;
import org.androidpush.utils.DBUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by huang on 2017/4/16 0016.
 */
public class CouDetailActivity extends Activity {

    private static final String LOGTAG = LogUtil
            .makeLogTag(CouDetailActivity.class);

    private String userId, teaCouId;
    private ListView couDatailLV;
    private TextView couNameTV;
    private Button applyLL, disapplyLL;
    private SelectCouInfoDao selectCouInfoDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xml_selectcou_detail);
        init();
        ConstantUtils.aetActionBar(this, getString(R.string.str_coudetail)); //设置自定义Actionbar
        String url = ConstantUtils.URL + "JxhtWeb/StuCouController/" + userId + "/querySelectCouRecordSigle?teaCouId=" + teaCouId;
        Log.d(LOGTAG, url);
        new couDetailAsyncTask().execute(url);
        setOnClickistenter();
    }

    /**
     * 控件初始化
     */
    private void init() {
        teaCouId = getIntent().getStringExtra("teaCouId");
        couDatailLV = (ListView) findViewById(R.id.id_selectcou_detail_list);
        couNameTV = (TextView) findViewById(R.id.id_selectcou_detail_couname);
        applyLL = (Button) findViewById(R.id.id_selectcou_apply);
        disapplyLL = (Button) findViewById(R.id.id_selectcou_disapply);
        userId = ConstantUtils.getUserId(this);
        selectCouInfoDao = DBUtils.getSelectCouInfoDao(this);
        initView();
    }

    /**
     * 从SQLite数据库获取课程数据加载UI
     */
    private void initView() {
        SelectCouInfo info = selectCouInfoDao.queryRaw("WHERE TEA_COU_ID = ?", teaCouId).get(0);
        List<Map<String, Object>> datalist = getData(getResources().getStringArray(R.array.strArray_couDetail), info);
        SimpleAdapter adapter = new SimpleAdapter(CouDetailActivity.this, datalist, R.layout.xml_selectcou_detail_item,
                new String[]{"name", "value"}, new int[]{R.id.id_coudetailitem_name, R.id.id_coudetailitem_value});
        couNameTV.setText(info.getCouName());
        couDatailLV.setAdapter(adapter);
        couDatailLV.setCacheColorHint(Color.TRANSPARENT);
    }

    /**
     * 监听按钮点击事件
     */
    private void setOnClickistenter() {
        /**
         * 选课申请
         */
        applyLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = ConstantUtils.URL + "JxhtWeb/StuCouController/" + userId +
                        "/insertStuCouRecord?teaCouId=" + teaCouId;
                Log.d(LOGTAG, url);
                requestWeb(url, teaCouId);
                applyLL.setEnabled(false); //使申请按钮失效
                applyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                disapplyLL.setEnabled(true);
                disapplyLL.setBackgroundColor(getResources().getColor(R.color.skyblue));
            }
        });
        /**
         * 退课申请
         */
        disapplyLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = ConstantUtils.URL + "JxhtWeb/StuCouController/" + userId +
                        "/deleteStuCouRecord?teaCouId=" + teaCouId;
                requestWeb(url, teaCouId);
                Log.d(LOGTAG, url);
                disapplyLL.setEnabled(false); //使退申按钮失效
                disapplyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                applyLL.setEnabled(true);
                applyLL.setBackgroundColor(getResources().getColor(R.color.skyblue));
            }
        });
    }
    /**
     * 选课退选网络访问
     */
    public void requestWeb(final String url, final String requestWay) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                String result = null;
                Request request = new Request.Builder().url(url).build();
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        result = (String) response.body().string();
                    }else {
                        result = "NULL";
                    }
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("result", result);
                    msg.setData(data);
                    mhandler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 异步访问请求网络
     */
    class couDetailAsyncTask extends
            AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return ConstantUtils.getDateFrom(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.d(LOGTAG + "Result", result);
            if(ConstantUtils.NET_ERROR.equals(result)) {
                applyLL.setEnabled(false);
                applyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                disapplyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                disapplyLL.setEnabled(false);
            }else {
                if ("SUCCESS".equals(result)) {
                    applyLL.setEnabled(false);
                    applyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                    disapplyLL.setEnabled(true);
                    disapplyLL.setBackgroundColor(getResources().getColor(R.color.skyblue));
                } else {
                    disapplyLL.setEnabled(false);
                    disapplyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                    applyLL.setEnabled(true);
                    applyLL.setBackgroundColor(getResources().getColor(R.color.skyblue));
                }
            }
        }
    }

    /**
     * 数据整理
     * @param names
     * @param dto
     * @return
     */
    private List<Map<String, Object>> getData(String[] names, SelectCouInfo dto) {
        List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
        List<String> values = new ArrayList<>();
        values.add(Long.toString(dto.getTeaCouId()));
        values.add(dto.getTeaName());
        values.add(dto.getCouCredit());
        values.add(dto.getTeaCouWeekTime() + Integer.toString(dto.getTeaCouStart()) + Integer.toString(dto.getTeaCouEnd()));
        values.add(dto.getTeaCouAddress());
        values.add(Integer.toString(dto.getTeaCouVolume()));
        values.add(dto.getCouProperty());
        values.add(dto.getMajName());
        values.add(Integer.toString(dto.getTeaCouSemester()));
        values.add(Integer.toString(dto.getTeaCouYear()));
        for (int i = 0; i < names.length; i++) {
            HashMap<String, Object> itemData = new HashMap<>();
            itemData.put("name", names[i]);
            itemData.put("value", values.get(i));
            datalist.add(itemData);
        }
        return datalist;
    }



    /**
     * Handler 线程更新UI
     */
    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String result = data.getString("result");
            Log.d(LOGTAG+"mhandler",result);
            if(ConstantUtils.SUCCESS.equals(result)){
                ConstantUtils.logToast(CouDetailActivity.this,"成功");
            }else if(ConstantUtils.FAILUER.equals(result)) {
                ConstantUtils.logToast(CouDetailActivity.this,"失败");
            }else if(ConstantUtils.CREDIT_ERROR.equals(result)){
                ConstantUtils.logToast(CouDetailActivity.this, "每学期选修课程总分不能超过4学分");
                disapplyLL.setEnabled(false);
                disapplyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                applyLL.setEnabled(true);
                applyLL.setBackgroundColor(getResources().getColor(R.color.skyblue));
            }else {
                ConstantUtils.logToast(CouDetailActivity.this,"发生错误");
                applyLL.setEnabled(false);
                applyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                disapplyLL.setBackgroundColor(getResources().getColor(R.color.gray));
                disapplyLL.setEnabled(false);
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        DBUtils.closeDB();
    }
}
